<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta
            name="viewport"
            content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"
        />
        <meta name="format-detection" content="telephone=no,email=no,date=no,address=no" />
        <title></title>
        <link rel="stylesheet" type="text/css" href="../../css/aui.css" />
        <script src="../../script/jquery.js"></script>
        <script src="../../CommonTool/commonNetWork.js"></script>

        <style>
            body {
                background-color: #03a9f4;
            }

            #frm-container {
                margin: 0 auto;
                width: 83%;
                height: 100%;
                border-radius: 20px;
                border: 2px solid white;
                padding: 5px 10px;
                background: white;
            }

            #footer {
                background: none;
                position: absolute;
                bottom: 0;
            }
        </style>
    </head>

    <body>
        <header class="aui-bar aui-bar-nav" id="aui-header">
            <div class="aui-pull-left aui-btn" onclick="close_win();">
                <span class="aui-iconfont aui-icon-left"></span>返回
            </div>
        </header>
        <div id="frm-container" class="aui-content-padded">
            <div class="aui-tab aui-margin-t-10 aui-margin-b-5 aui-font-size-18">
                <div style="color: #03a9f4; margin: 0 auto">请设置头像</div>
            </div>
            <div class="aui-hr" style="width: 90%; margin: 0 auto; border-top: 0.05rem solid #03a9f4"></div>
            <div>
                <img  id="base64Data" src="">
                <img
                    id="user-info-avatar"
                    src="../../image/head.png"
                    style="
                        width: 6rem;
                        height: 6rem;
                        border-radius: 50%;
                        margin: 0 auto;
                        margin-top: 1rem;
                        margin-bottom: 0.5rem;
                    "
                    onclick="profile_select();"
                />
                <div style="color: #aaaaaa; text-align: center">点击设置头像</div>
            </div>
            <section class="aui-content-padded">
                <div
                    id="ok-btn"
                    class="aui-btn aui-btn-block aui-btn-info aui-btn-sm aui-font-size-18"
                    style="margin-top: 2.5rem"
                    tapmode
                    onclick="ok_click();"
                >
                    确认
                </div>
                <div
                    class="aui-btn aui-btn-block aui-btn-info aui-btn-sm aui-font-size-18"
                    style="margin-top: 1rem; margin-bottom: 5rem; background-color: #b2b2b2"
                    onclick="cancle();"
                >
                    取消
                </div>
                <input ty>
            </section>
        </div>
    </body>
    <script type="text/javascript" src="../../script/api.js"></script>
    <script type="text/javascript">
        var login_user_info;
        var avatar_url;
        var local_avatar_info = "../../../image/head.png";
        var local_avatar_info1= "../../../image/head.png";
        var jsfun;
        var token;
        var userid = "";
        var ftpRequestTest;
        var fsDir;
        var imgName;
        var keyid;
        var avatarUrl;
        var avatarUrlNew;
        var fsName;
        apiready = function () {
            login_user_info = api.pageParam.login_user_info;
            token = api.pageParam.token;
            ftpRequestTest = api.require("ftpRequest");
            fsName = api.require('fs');
            userid = api.pageParam.uid;
            keyid = api.pageParam.keyid;
            fsDir = api.fsDir;
            api.parseTapmode();
            $api.removeCls("ok-btn", "active");
            //用户头像
            getAvatar();
            //适配iOS7+，Android4.4+状态栏沉浸式效果，详见config文档statusBarAppearance字段
            $api.fixStatusBar($api.byId("aui-header"));
            $api.css(
                $api.byId("frm-container"),
                "height:" + (api.frameHeight - 48 - $api.offset($api.byId("aui-header")).h) * 1.23 + "px;"
            );
        };
        function getAvatar() {
            $.ajax({
                url: CommonUrl + "/tSysUser/queryById?id=" + keyid,
                method: "get",
                dataType: "json",
                contentType: "application/json",
                headers: {
                    Authorization: `Bearer ${token}`,
                    CacheControl: "no-cache",
                },
                success: function (data) {
                    avatarUrl = JSON.parse(JSON.stringify(data.data.imageUrl));
                    $api.byId("user-info-avatar").src = avatarUrl;
                },
                error: function (err) {
                    alert(JSON.stringify(err) + "打印头像失败");
                },
            });
        }
        function get_current_user_info(login_userid) {
            var userID = login_userid;
            api.ajax(
                {
                    url: $api.getStorage("api_url") + "/lansys/user/getUserInfo",
                    method: "post",
                    timeout: 5,
                    data: {
                        values: {
                            userID: userID,
                            // token: token,
                            //msgcode: $api.val($api.byId('code')),
                        },
                    },
                },
                function (ret, err) {
                    if (ret) {
                        var response = JSON.stringify(ret);
                        console.log(JSON.stringify(ret));
                        //api.alert({msg:response});
                        if (ret.result == "success") {
                            if (ret.avatar == null) {
                                $api.byId("user-info-avatar").src = "../../../image/head.png";
                                $api.byId("user-info-avatar").style.background = "white";
                            } else {
                                $api.byId("user-info-avatar").src = ret.avatar;
                            }
                        }
                    }
                }
            );
        }
        //add by gxl
        function profile_select() {
            api.actionSheet(
                {
                    title: "头像设置",
                    cancelTitle: "取消",
                    //destructiveTitle: '红色警告按钮',
                    buttons: ["从本机相册选择", "拍摄"],
                },
                function (ret, err) {
                    var index = ret.buttonIndex;
                    if (index == 1) {
                        var has = hasPermissionObj("storage");
                        if (!has || !has[0] || !has[0].granted) {
                            api.confirm(
                                {
                                    title: "提醒",
                                    msg: "没有获得 " + "存储空间" + " 权限\n是否前往设置？",
                                    buttons: ["去设置", "取消"],
                                },
                                function (ret, err) {
                                    if (1 == ret.buttonIndex) {
                                        reqPermission("storage");
                                    }
                                }
                            );
                            return false;
                        } else {
                            api.getPicture(
                                {
                                    sourceType: "library",
                                    encodingType: "jpg",
                                    mediaValue: "pic",
                                    destinationType: "url",
                                    allowEdit: true,
                                    quality: 100,
                                    targetWidth: 1000,
                                    targetHeight: 1000,
                                    saveToPhotoAlbum: false,
                                },
                                function (ret, err) {
                                    $api.byId("user-info-avatar").src = ret.data;
                                    if (ret.data) {
                                        local_avatar_info1 = ret.data;
                                        // $api.byId('user-info-avatar').src = ret.data;
                                        var imageCrop = api.require("imageCrop");
                                        imageCrop.clipPhoto(
                                            {
                                                imgPath: ret.data,
                                                height: 300,
                                                width: 300,
                                            },
                                            function (ret, err) {
                                                if (ret) {
                                                    $api.byId("user-info-avatar").src = ret.imgPath;
                                                    local_avatar_info = ret.imgPath;
                                                    // api.toast({
                                                    //     msg: local_avatar_info, //上传的头像的本地地址
                                                    //     duration: 2000,
                                                    //     location: "bottom",
                                                    // });
                                                } else {
                                                    // alert(JSON.stringify(err));
                                                }
                                            }
                                        );
                                    } else {
                                    }
                                }
                            );
                        }
                    } else if (index == 2) {
                        var has = hasPermissionObj("camera");
                        if (!has || !has[0] || !has[0].granted) {
                            api.confirm(
                                {
                                    title: "提醒",
                                    msg: "没有获得 " + "相机" + " 权限\n是否前往设置？",
                                    buttons: ["去设置", "取消"],
                                },
                                function (ret, err) {
                                    if (1 == ret.buttonIndex) {
                                        reqPermission("camera");
                                    }
                                }
                            );
                            return false;
                        } else {
                            api.getPicture(
                                {
                                    sourceType: "camera",
                                    encodingType: "jpg",
                                    mediaValue: "pic",
                                    destinationType: "url",
                                    allowEdit: true,
                                    quality: 100,
                                    saveToPhotoAlbum: false,
                                },
                                function (ret, err) {
                                    if (ret.data) {
                                        local_avatar_info1 = ret.data;
                                        if (ret.data) {
                                            // local_avatar_info = ret.data;
                                            // $api.byId('user-info-avatar').src = ret.data;
                                            var imageCrop = api.require("imageCrop");
                                            imageCrop.clipPhoto(
                                                {
                                                    imgPath: ret.data,
                                                    height: 300,
                                                    width: 300,
                                                },
                                                function (ret, err) {
                                                    alert(ret);
                                                    if (ret) {
                                                        $api.byId("user-info-avatar").src = ret.imgPath;
                                                        local_avatar_info = ret.imgPath;
                                                    } else {
                                                        //alert(JSON.stringify(err));
                                                    }
                                                }
                                            );
                                        }
                                    } else {
                                    }
                                }
                            );
                        }
                    }
                }
            );
        }

function ok_click() {
        
    const timestamp = Date.now();
    const imgName = userid + timestamp + ".jpg";
    const filePath = local_avatar_info; 

    if (!filePath) {
        alert('Please select a photo first.');
        return;
    }
    // fsName.read 读出来是空
    
    api.readFile({
        path:filePath,
    }, function(ret, err){
        if(ret && ret.data){
            alert('读取'+ret.data) 
        
            let bloba = new Blob([ret.data], { type: 'image/jpeg' });
            // 将 Blob 转换为 Base64
            
        
            // const formData = new FormData();
            // formData.append('base64Data',base64Data);
            // formData.append('fileName', imgName);
            fetch(CommonUrl + "/images/uploadImages", {
            method: "POST",
            headers: {
                Authorization: `Bearer ${token}`,
                'Content-Type': 'application/octet-stream',
                "fileName":'img.jpg'
            },
            body: bloba
        })
        .then(response => response.json())
        .then(data => {
            alert('上传成功');
            console.log(data);
        })
        .catch(error => {
            alert('上传失败');
            console.error(error);
        })

    } else {
        alert('读取文件失败: ' + JSON.stringify(err));
    }
})
              // 将二进制数据转换为 Blob
        // const bloba = new Blob([ret.data], { type: 'image/jpeg' });
        // const formData = new FormData();
        // formData.append('file', bloba, 'image.jpg'); // 假设文件名是 image.jpg

           
            // $.ajax({
            //     url: CommonUrl + "/images/uploadImages",
            //     method: "post",
            //     headers: {
            //         Authorization: `Bearer ${token}`,
            //     },
            //     data:formData,
            //     success: function(data) {
            //        alert(JSON.stringify(data)+'文件成功');
            //     },
            //     error: function(error) {
            //         alert(JSON.stringify(error));
            //     },
            // })
            // $.ajax({
            //     url: CommonUrl + "/images/uploadImages",
            //     method: "post",
               
            //     headers: {
            //         Authorization: `Bearer ${token}`,
            //         'Content-Type': 'application/json', // 明确设置 Content-Type
            //     },
            //     data:JSON.stringify({
            //         base64Data: base64Data,
            //         fileName:  imgName
            //     }),
            //     success: function (data) {
            //          alert(JSON.stringify(data)+'上传成功')
            //     },
            //     error: function (error) {
            //         alert(JSON.stringify(error)+'上传失败');
            //     },
            // });

            // fetch(CommonUrl + '/images/uploadImages', {
            //     method: 'POST',
            //     processData: false, // 不要处理发送的数据
            //     contentType: false,//不要设置格式
            //     headers: {
            //         Authorization: `Bearer ${token}`,
            //     },
            //     body: JSON.stringify({
            //         base64Data: base64Data,
            //         fileName: imgName // 可选
            //     })
            //   .then(data => {
            //       alert('上传成功');
            //   })
            //   .catch(e => {
            //       alert('上传失败: ' + e);
            //   })
            //   })


//     // 1. 用 api.readFile 读取本地文件为 base64
//     api.readFile({
//         path: filePath
//     }, function(ret, err) {
//         if (ret && ret.data) {
//             const base64Data = binaryToBase64(ret.data);
//             alert(base64Data)
//             if (base64Data.length % 4 !== 0) {
//     alert('字符串长度不是 4 的倍数，可能不是有效的 Base64 编码');
// } else {
// alert('是有效的编码')}
//             alert("data:image/jpeg;base64," + base64Data);
//             // 2. base64 转 Blob
//             const byteString = atob(base64Data.split(',')[1]);
//             const mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
//             const ab = new ArrayBuffer(byteString.length);
//             const ia = new Uint8Array(ab);
//             for (let i = 0; i < byteString.length; i++) {
//                 ia[i] = byteString.charCodeAt(i);
//             }
//             const blob = new Blob([ab], { type: mimeString });

//             // 3. 生成 File 对象
//             const file = new File([blob], imgName, { type: mimeString });

//             // 4. FormData 上传
//             const formData = new FormData();
//             formData.append('imageFile', file);

//             fetch(CommonUrl + '/images/uploadImages', {
//                 method: 'POST',
//                 headers: {
//                     Authorization: `Bearer ${token}`,
//                 },
//                 body: formData
//             }).then(res => res.json())
//               .then(data => {
//                   alert('上传成功');
//               })
//               .catch(e => {
//                   alert('上传失败: ' + e);
//               });
//         } else {
//             alert('读取文件失败: ' + JSON.stringify(err));
//         }
//     });
            // ajax的方式
            // const timestamp= Date.now();
            // const imgName =userid +timestamp +".jpg";
            // const filePath =local_avatar_info;// 裁剪后的本地图片路径(ret.imgPath)
            // if(!filePath){
            // alert('please select a photo first.');
            // return
            // }
            // $.ajax({
            //     url: CommonUrl + "/images/uploadImages",
            //     method: "post",
            //     processData: false, // 告诉 jQuery 不要处理发送的数据
            //     contentType: false, // 告诉 jQuery 不要设置 Content-Type 头
            //     headers: {
            //         Authorization: `Bearer ${token}`,
            //     },
            //     data: {
            //         files: { 
            //           imageFile:filePath//直接传本地路径
            //         }
                    
            //     },
            //     success: function (data) {
            //          alert(JSON.stringify(data))
            //     },
            //     error: function (error) {
            //         alert(JSON.stringify(error));
            //     },
            // });

             // 利用ftp服务上传本地路径
            //  ftpRequestTest.upload(
            //     {
            //         // url: `${ftpURL}${userid}`,
            //         url: `${ftpURL}${imgName}`,
            //         // url:`${ftpURL}+'1111'`,
            //         localPath:local_avatar_info,
            //         name: "ftpuser",
            //         password: "password",
            //     },
            //     function (ret, err) {
            //         if (ret.eventType == "success") {
            //             alert("上传成功");
            //             //头像变成在线链接
            //             UpdataAvatar()
            //         } else if (ret.eventType == "progress") {
            //             api.alert(JSON.stringify(ret));
            //             alert("正在上传");
            //         } else {
            //             api.alert({ msg: JSON.stringify(err) });
            //             alert("上传失败");
            //         }
            //     }
            // );

        }
        //修改头像成功后要改后端接口
        function UpdataAvatar() {
            $.ajax({
                url: CommonUrl + "/tSysUser/update",
                method: "post",
                dataType: "json",
                contentType: "application/json",
                headers: {
                    Authorization: `Bearer ${token}`,
                },
                data: JSON.stringify({
                    id: keyid,
                    imageUrl:imgSourceUrl+'/uploadTest/uploadAudio/'+imgName,
                    // imageUrl: imgSourceUrl + "/" + imgName,
                }),
                success: function (data) {
                    avatarUrlNew = JSON.parse(JSON.stringify(data.data.imageUrl));
                    // 上传成功后立即刷新页面
                    api.execScript({
                        name: "MainMenu",
                        url: "./../MainMenu.html",
                        script: "location.reload()",
                    });
                },
                error: function (error) {
                    alert(JSON.stringify(error));
                },
            });
        }
     // 

     function convertBlobToBase64(blob) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = function() {
            resolve(reader.result);
        };
        reader.onerror = function(error) {
            reject(error);
        };
        reader.readAsDataURL(blob);
    });
}
        function close_win() {
            api.openWin({
                name: "MainMenu",
                url: "./../MainMenu.html",
                reload: true,
                pageParam: {
                    uid: userid,
                    token: token,
                    keyid: keyid,
                    avatarUrl: avatarUrlNew,
                },
            });
        }
        function reqPermission(one_per, callback) {
            var perms = new Array();
            if (one_per) {
                perms.push(one_per);
            } else {
                perms = ["library", "camera"];
            }
            api.requestPermission(
                {
                    list: perms,
                    code: 100001,
                },
                function (ret, err) {
                    if (callback) {
                        callback(ret);
                        return;
                    }
                    var str = "请求结果：\n";
                    str += "请求码: " + ret.code + "\n";
                    str += '是否勾选"不再询问"按钮: ' + (ret.never ? "是" : "否") + "\n";
                    str += "请求结果: \n";
                    var list = ret.list;
                    for (var i in list) {
                        str += list[i].name + "=" + list[i].granted + "\n";
                    }
                    console.log(JSON.stringify(ret));
                }
            );
        }

        function hasPermissionObj(one_per) {
            var perms = new Array();
            if (one_per) {
                perms.push(one_per);
            } else {
                perms = ["library", "camera"];
            }
            var rets = api.hasPermission({
                list: perms,
            });
            if (!one_per) {
                return;
            }
            return rets;
        }
        function cancle() {
            api.closeWin({});
        }
    </script>
</html>
